package com.niit.mobileDevide.appusagetime;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AppUsageTimeReducer extends Reducer<Text, Text, Text, Text> {

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        List<Double> usageTimes = new ArrayList<>();
        for (Text val : values) {
            usageTimes.add(Double.parseDouble(val.toString()));
        }

        // 计算平均App Usage Time
        double sum = usageTimes.stream().mapToDouble(Double::doubleValue).sum();
        double average = sum / usageTimes.size();

        // 统计小于和大于平均值的用户数
        long belowAverageCount = usageTimes.stream().filter(time -> time < average).count();
        long aboveAverageCount = usageTimes.size() - belowAverageCount;

        // 构建输出字符串
        StringBuilder output = new StringBuilder();
        output.append("Average App Usage Time (min/day): ").append(average).append("\n");
        output.append(key.toString()).append(" users below average: ").append(belowAverageCount).append("\n");
        output.append(key.toString()).append(" users above average: ").append(aboveAverageCount);

        // 输出结果
        context.write(key, new Text(output.toString()));
    }
}